// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './All.less';

// 图片

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ fu, loading }) => ({
  fu,
  loading: loading.models.fuRule,
}))
@Form.create()
class Option extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    OptionsDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      if (record[dataIndex] === '期权合计') {
        return true;
      }
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({
      searchText: selectedKeys[0],
    });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    const that = this;
    const {
      fu: { optionsFilters },
    } = this.props;
    return [
      /*    {
            title: '序号',
            dataIndex: 'p',
          }, */
      {
        title: '股票代码',
        ...this.getColumnSearchProps('name'),
        width: 200,
        dataIndex: 'name',
        align: 'center',
        sorter: (a, b) => {
          const c = [a.name, b.name].sort();
          if (c[0] === a.name) {
            return 1;
          }
          return -1;
        },
      },
      {
        title: '类型',
        dataIndex: 'typename',
        width: 80,
        align: 'center',
        filters: [
          {
            text: 'SP',
            value: 'SP',
          },
          {
            text: 'SC',
            value: 'SC',
          },
        ],
        onFilter: (value, record) => {
          if (record.name === '期权合计') {
            return true;
          }
          if (record.typename !== undefined) {
            return record.typename.indexOf(value) === 0;
          }
        },
      },
      {
        title: '执行价',
        dataIndex: 'strikeprice',
        align: 'center',
        sorter: (a, b) => a.strikeprice - b.strikeprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '当前价',
        dataIndex: 'stockprice',
        align: 'center',
        sorter: (a, b) => a.stockprice - b.stockprice,
        /* render: text => {
          return <span >{typeof value === 'number' || typeof value === 'string' ? NumberDivide((Math.floor(text*100)/100).toString()) : null}</span>;
        }, */
      },

      {
        title: '距执行幅度',
        dataIndex: 'pricerate',
        align: 'center',
        sorter: (a, b) => a.pricerate - b.pricerate,
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{`${FormatnumberZero(text * 100, 2)}%`}</span>;
          }
          return null;
        },
      },
      {
        title: '成本价',
        dataIndex: 'costprice',
        align: 'center',
        sorter: (a, b) => a.costprice - b.costprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },

      {
        title: '现价',
        dataIndex: 'newprice',
        sorter: (a, b) => a.newprice - b.newprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },

      {
        title: '剩余期权比',
        dataIndex: 'premiumrate',
        sorter: (a, b) => a.premiumrate - b.premiumrate,
        align: 'center',
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{`${FormatnumberZero(text * 100, 2)}%`}</span>;
          }
          return null;
        },
      },
      {
        title: '股数',
        dataIndex: 'stocknumber',
        sorter: (a, b) => a.stocknumber - b.stocknumber,
        align: 'center',
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '当日盈亏',
        dataIndex: 'thisincome',
        width: 120,
        sorter: (a, b) => {
          if (b.name === '期权合计') {
            return false;
          }
          return a.thisincome - b.thisincome;
        },
        align: 'center',
        render: (tags, record) => {
          const bili = record.thisincome / (record.stocknumber * record.costprice);
          let color = '';
          if (bili < -0.4) {
            color = '#be5eed';
          } else if (bili > -0.4 && bili < -0.2) {
            color = '#9218cd';
          } else if (bili > -0.2 && bili < 0) {
            color = '#601386';
          } else if (bili == 0) {
            color = '#201a23';
          } else if (bili > 0 && bili < 0.2) {
            color = '#f86d75';
          } else if (bili > 0.2 && bili < 0.4) {
            color = '#f3353f';
          } else if (bili > 0.2) {
            color = '#c70f19';
          } else {
            color = '#8a0a11';
          }
          return <span style={{ color }}>{tags}</span>;
        },
      },
      {
        title: '盈亏金额',
        dataIndex: 'allincome',
        width: 120,
        align: 'center',
        sorter: (a, b) => {
          if (b.name === '期权合计') {
            return false;
          }
          return a.allincome - b.allincome;
        },
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '初始期权金',
        dataIndex: 'allpremium',
        width: 120,
        align: 'center',
        sorter: (a, b) => {
          if (b.name === '期权合计') {
            return false;
          }
          return a.allpremium - b.allpremium;
        },
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '剩余期权金',
        dataIndex: 'remainpremium',
        width: 120,
        sorter: (a, b) => {
          if (b.name === '期权合计') {
            return false;
          }
          return a.remainpremium - b.remainpremium;
        },
        align: 'center',
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '期权金',
        dataIndex: 'unkown2',
        width: 120,
        sorter: (a, b) => {
          if (b.name === '期权合计') {
            return false;
          }
          return a.unkown2 - b.unkown2;
        },
        align: 'center',
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },

      {
        title: '操作时间',
        dataIndex: 'tradedate',
        width: 100,
        align: 'center',
        sorter: (a, b) => DateStamp(a.tradedate) - DateStamp(b.tradedate),
      },
      {
        title: '到期时间',
        dataIndex: 'expiry',
        width: 100,
        align: 'center',
        sorter: (a, b) => DateStamp(a.expiry) - DateStamp(b.expiry),
      },
      {
        title: '剩余天数',
        dataIndex: 'remaindays',
        width: 80,
        align: 'center',
        sorter: (a, b) => a.remaindays - b.remaindays,
      },
      {
        title: '头寸规模',
        dataIndex: 'sumprice',
        align: 'center',
        width: 120,
        sorter: (a, b) => {
          if (b.name === '期权合计') {
            return false;
          }
          return a.sumprice - b.sumprice;
        },
        fixed: 'right',
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
    });
    /* 导入列表数据 */
    dispatch({
      type: 'fu/GetFssFundOptionsList',
      payload: {
        groupId: 2,
        currentDataSource: extra.currentDataSource,
      },
      callback: res => {},
    });
  };

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      loading,
      fu: { options },
    } = this.props;
    const { listLoading, selectedRows, premium } = this.state;
    let columns = [];
    const optionsList = [];
    if (columns.length === 0 && options.code === 1) {
      columns = this.getColumns();
    }
    return (
      <PageHeaderWrapper title="傅总期权持仓">
        <Card>
          {options.code === 0 ? (
            <Loading />
          ) : (
            <div>
              <div style={{ margin: 8, fontSize: '1rem' }}>
                共计：{this.state.currentDataSource.length - 1}
              </div>
              <StandardTable
                bordered
                selectedRows={selectedRows}
                loading={listLoading}
                data={options}
                columns={columns}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                pagination={false}
                onChange={this.handleStandardTableChange}
                scroll={{ x: 1900, y: 618 }}
                rowClassName={(record, index) =>
                  record.name === '期权合计' ? styles.statisticssTableBackground : styles.ffffff
                }
              />
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'fu/GetFssFundOptionsList',
      payload: {
        groupId: 2,
        currentDataSource: this.state.currentDataSource,
      },
      callback: res => {
        this.setState({
          currentDataSource: res.data,
        });
      },
    });
  }

  componentWillUnmount() {}
}

export default Option;
